package javabase.demo03;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

public class LockPractice {

    private static int count = 0;
    private static final ReentrantLock reentrantLock = new ReentrantLock();
    private static final ReadWriteLock readWriteLock = new ReentrantReadWriteLock();

    public static void main(String[] args) throws InterruptedException {
        // 1. ReentrantLock基本使用
        demonstrateReentrantLock();

        // 2. 可中断锁
        demonstrateInterruptibleLock();

        // 3. 公平锁 vs 非公平锁
        demonstrateFairLock();

        // 4. 读写锁
        demonstrateReadWriteLock();

        // 5. Condition条件变量
        demonstrateCondition();

    }

    private static void demonstrateReentrantLock() throws InterruptedException {
        System.out.println("\n=== ReentrantLock基本使用 ===");
        count = 0;
        Thread t1 = new Thread(() -> {
            for (int i = 0; i < 10000; i++) {
                reentrantLock.lock(); // 获取锁
                try {
                    count++;
                } finally {
                    reentrantLock.unlock(); // 释放锁
                }
            }
        });

        Thread t2 = new Thread(() -> {
            for (int i = 0; i < 10000; i++) {
                reentrantLock.lock();
                try {
                    count++;
                } finally {
                    reentrantLock.unlock();
                }
            }
        });

        t1.start();
        t2.start();
        t1.join();
        t2.join();

        System.out.println("ReentrantLock计数: " + count);


        // 带超时的尝试获取锁
        boolean acquired = reentrantLock.tryLock();
        if (acquired) {
            try {
                System.out.println("尝试获取锁成功");
            } finally {
                reentrantLock.unlock();
            }
        } else {
            System.out.println("尝试获取锁失败");
        }

        // 带超时的尝试获取锁
        try {
            acquired = reentrantLock.tryLock(1, TimeUnit.SECONDS);
            if (acquired) {
                try {
                    System.out.println("带超时的尝试获取锁成功");
                } finally {
                    reentrantLock.unlock();
                }
            } else {
                System.out.println("带超时的尝试获取锁失败");
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
    private static void demonstrateInterruptibleLock() {
        System.out.println("\n=== 可中断锁 ===");
        Thread t1 = new Thread(() -> {
            try {
                // 可中断地获取锁
                reentrantLock.lockInterruptibly();
                try {
                    System.out.println("线程1获取到锁，将睡眠5秒");
                    Thread.sleep(5000);
                } finally {
                    reentrantLock.unlock();
                }
            } catch (InterruptedException e) {
                System.out.println("线程1在等待锁时被中断");
            }
        });

        Thread t2 = new Thread(() -> {
            try {
                // 可中断地获取锁
                reentrantLock.lockInterruptibly();
                try {
                    System.out.println("线程2获取到锁");
                } finally {
                    reentrantLock.unlock();
                }
            } catch (InterruptedException e) {
                System.out.println("线程2在等待锁时被中断");
            }
        });

        t1.start();
        try {
            Thread.sleep(100); // 确保t1先获取锁
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        t2.start();

        // 2秒后中断t2
        try {
            Thread.sleep(2000);
            t2.interrupt(); // 中断t2线程
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    private static void demonstrateFairLock() {
        System.out.println("\n=== 公平锁 vs 非公平锁 ===");

        // 公平锁
        ReentrantLock fairLock = new ReentrantLock(true);
        // 非公平锁
        ReentrantLock unfairLock = new ReentrantLock(false);

        System.out.println("公平锁: " + fairLock.isFair());
        System.out.println("非公平锁: " + unfairLock.isFair());

        // 测试公平性
        testLockFairness(fairLock, "公平锁");
        testLockFairness(unfairLock, "非公平锁");
    }

    private static void testLockFairness(ReentrantLock lock, String lockType) {
        System.out.println("\n测试" + lockType + "的公平性:");

        for (int i = 0; i < 5; i++) {
            final int threadId = i;
            new Thread(() -> {
                for (int j = 0; j < 2; j++) {
                    lock.lock();
                    try {
                        System.out.println(lockType + " - 线程" + threadId + "获取到锁");
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    } finally {
                        lock.unlock();
                    }
                }
            }).start();

            // 稍微延迟启动，让线程按顺序排队
            try {
                Thread.sleep(10);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    private static void demonstrateReadWriteLock() throws InterruptedException {
        System.out.println("\n=== 读写锁 ===");

        ReadWriteLock rwLock = new ReentrantReadWriteLock();
        String[] data = new String[1]; // 共享数据

        // 写线程
        Thread writer = new Thread(() -> {
            rwLock.writeLock().lock(); // 获取写锁
            try {
                System.out.println("写线程开始写入数据");
                Thread.sleep(1000); // 模拟写入耗时
                data[0] = "Hello, World!";
                System.out.println("写线程完成数据写入");
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                rwLock.writeLock().unlock(); // 释放写锁
            }
        });

        // 读线程
        Runnable reader = () -> {
            rwLock.readLock().lock(); // 获取读锁
            try {
                System.out.println("读线程 " + Thread.currentThread().getName() +
                        " 读取数据: " + data[0]);
                Thread.sleep(500); // 模拟读取耗时
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                rwLock.readLock().unlock(); // 释放读锁
            }
        };

        writer.start();

        // 等待写线程开始
        Thread.sleep(100);

        // 启动多个读线程
        for (int i = 0; i < 5; i++) {
            new Thread(reader, "R" + i).start();
        }

        writer.join();
    }

    private static void demonstrateCondition() {
        System.out.println("\n=== Condition条件变量 ===");

        ReentrantLock lock = new ReentrantLock();
        Condition condition = lock.newCondition();


        Thread t1 = new Thread(() -> {
            lock.lock();
            try {
                System.out.println("线程1等待条件");
                condition.await(); // 等待条件
                System.out.println("线程1被唤醒");
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                lock.unlock();
            }
        });

        Thread t2 = new Thread(() -> {
            lock.lock();
            try {
                System.out.println("线程2执行一些工作");
                Thread.sleep(2000);
                condition.signal(); // 唤醒一个等待线程
                System.out.println("线程2发出信号");
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                lock.unlock();
            }
        });

        t1.start();
        t2.start();

        try {
            t1.join();
            t2.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
